<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24/024
 * Time: 20:37
 */

namespace app\admin\model;

use think\Db;
use think\facade\Session;

class Chapter extends \think\Model
{
    protected $table = 'sy_tk_chapters';

    /**
     * 获取单条
     * @param $id
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public function _findOne($id){
        return $this->where([['id', '=', $id]])->find();
    }

    
    /**
    * 通过名称获取信息
    */
    public function _findByName($name){
        return $this->where([['chapter_title', '=', $name]])->find();
    }
    
    //校验用户名是否存在
    public function _checkName($value){
        $data = $this->where([['chapter_title', '=', $value]])->find();
        if(!empty($data)){
            $this->error = '已存在';
            return false;
        }
        return true;
    }
    

    /**
    * 校验是否被冻结
    */
    public function _checkStatus($id){
        $data = $this->where(array('id'=>$id, 'status'=>1))->find();
        if(empty($data)){
            $this->error = '已禁用';
            return false;
        }
        return true;
    }

    /**
     * 列表
     * @param array $condition
     * @param int $page_size
     * @param string $order_by
     * @return \think\Paginator
     */
    public function _list($condition = [], $page_size = PAGE_SIZE_ADMIN, $order_by = 'sort asc'){
        $obj = $this->alias('p')
            ->field('p.*,c.cate_title')
            ->leftJoin('sy_tk_cates c','c.id=p.cate')
            ->order('p.id desc');
        $result = get_page($obj, $condition, $page_size);
       
        return $result;
    }

    /**
     * 添加
     * @param $post
     * @return bool
     */
    public function _create($post){
//        $title = trim($post['chapter_title']);
//        $admin = $this->where([['chapter_title', '=', $title]])->find();
//        if($admin){
//            $this->error = '已存在';
//            return false;
//        }
        $insert = [
            'chapter_title' => $post['chapter_title'],
            'cate' => $post['cate'],
            'create_at' => time(),

        ];
        if(!$this->insert($insert)){
            $this->error = '操作失败';
            return false;
        }
        return true;
    }


    /**
     * 删除
     * @param $id
     * @return bool
     */
    public function _remove($id){
        $result = $this->_findOne($id);
        if(!$result){
            $this->error = '无此';
            return false;
        }
        if(!$result->delete()){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }
    /**
     * 批量删除
     * @param $id
     * @return bool
     */
    public function _removeAll($id){
        $ret = $this->where([['id', 'in', $id]])->delete();
        if(!$ret){
            $this->error = '操作失败';
            return false;
        }
        
        return true;
    }


    /**
     * 详情
     * @param $id
     * @return array|bool
     */
    public function _detail($id){
        $result = $this->_findOne($id)->toArray();
        if(!$result){
            $this->error = '无此数据';
            return false;
        }
        return $result;
    }


    /**
     * 修改
     * @param $post
     * @return bool
     */
    public function _modify($post){
        $result = $this->_findOne($post['id']);
        if(empty($result)){
            $this->error = '不存在';
            return false;
        }
        $data = $this->where([['chapter_title', '=', trim($post['chapter_title'])]])->find();
        if(!empty($data)){
            if($data->id != $result->id){
                $this->error = '已存在';
                return false;
            }
        }
        if(isset($post['chapter_title'])) $result->chapter_title = trim($post['chapter_title']);
        if(isset($post['cate'])) $result->cate = $post['cate'];
        if($result->save() === false){
            $this->error = '操作失败';
            return false;
        }
        
        
        return true;
    }

    /**
    * 设置状态
    */
    public function _setStatus($request){
        $ff = $request['ff'];
        $id = $request['id'];
        if($ff == 1){
            $success = "停用成功";
            $error = "停用失败";
        }elseif($ff == -1){
            $success = "启用成功";
            $error = "启用失败";
        }
        
        
        $where = array('id'=>$id,'status'=>$ff);

        $data = $this->where($where)->find();
        if(empty($data)){
            $this->error = '该数据状态已改变';
            
            return false;
        }
        $data->status = -$ff;
        $ret = $data->save();
        if(!$ret){
            $this->error = $error;
            return false;
        }
        
        
        return true;
    }
    

    /**
    * 数据总条数
    */
    public function _count($where = []){
        return $this->alias('u')->where($where)->count();
    }

    /**
    * 获取条件
    */
    public function _where($request){
        $p = isset($request['page']) ? $request['page'] : 1;
        $start = isset($request['start']) ? $request['start'] : '';
        $end = isset($request['end']) ? $request['end'] : '';
        $cate = isset($request['cate']) ? $request['cate'] : '';
        $chapter_title = isset($request['chapter_title']) ? $request['chapter_title'] : '';
        
        $request['page'] = $p;
        $request['start'] = $start;
        $request['end'] = $end;
        $request['cate'] = $cate;
        $request['chapter_title'] = $chapter_title;
        $search = $request;
        $tmp = $request;
        foreach($tmp as $k=>$v){
            if(empty($v)){
                unset($tmp[$k]);
            }
        }
        
        $where = '';
        foreach($tmp as $k=>$v){
            if($k == 'start'){
                $start = strtotime($v);
                $where .= "created >= $start and ";
            }elseif($k == 'end'){
                $end = strtotime($v) + 24*3600;
                $where .= "created <= $end and ";
            }elseif($k == 'chapter_title'){
                $where .= "chapter_title like '%$v%' and ";
            }elseif($k == 'cate'){
                $where .= "cate = $v and ";
            }
        }
        if(!empty($where)){
            $where = substr($where, 0, -4);
        }
        return array('search'=>$search,'where'=>$where);
    }

    /**
     * 获取题库章节列表
     */
    public function _get_chapter_list($cate,$uid){
        $data = $this->where('cate',$cate)->field('id,chapter_title')->all()->toArray();
        foreach ($data as $k=>$v){
            $maps['cate']           = $cate;
            $maps['chapter_cate']   = $v['id'];
            $maps['chapter_type']   = 1;
            $chapter_detail = ChapterDetail::where($maps)->field('id,detail_title')->all()->toArray();
            $all_total = 0;
            $all_done  = 0;
            foreach ($chapter_detail as $kk=>$vv){
                $back_info = $this->_get_all_and_done($vv['id'],$uid);
                $chapter_detail[$kk]['total_number'] = $back_info['total'];
                $chapter_detail[$kk]['done_number']  = $back_info['done'];
                $all_total = $all_done+$back_info['total'];
                $all_done  = $all_done+$back_info['done'];
            }
            $data[$k]['_child']       = $chapter_detail;
            $data[$k]['total_number'] = $all_total;
            $data[$k]['done_number']  = $all_done;
        }
     return $data;
    }

    /**
     * 获取已完成和总题数
     */
    public function _get_all_and_done($detail_id,$uid){
        $total = Db::name('tk_single')->where('detail_id',$detail_id)->count();
        $maps0['detail_id'] = $detail_id;
        $maps0['uid']       = $uid;
        $right = Db::name('tk_record')->where($maps0)->value('right_number');
        $wrong = Db::name('tk_record')->where($maps0)->value('wrong_number');
        if(!$total){
            $total = 0;
        }
        if(!$right){
            $right = 0;
        }
        if(!$wrong){
            $wrong = 0;
        }
        $done = $right+$wrong;
        $back['total'] = $total;
        $back['done']  = $done;
        return $back;
    }

}